package com.sdx.console.content.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qcloud.vod.response.VodUploadCommitResponse;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.PropertiesService;
import com.sdx.third.TencentVideoApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.content.entity.*;
import com.sdx.console.content.service.*;
import com.sdx.console.content.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;

/**
 * 章节管理 接口
 */
@RequestMapping("/content/resContentChapter")
@Controller
public class ResContentChapterController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(ResContentChapterController.class);
    private static final String MODEL = "/content/resContentChapter";

    @Resource
    private PropertiesService propertiesService;

    @Resource
	private ResContentChapterService resContentChapterService;

    @Resource
    private ResContentMainService contentMainService;

	private void initContentMain(ModelAndView view,int contentId) {
		ResContentMain contentMain = contentMainService.queryById(contentId);
		view.addObject("contentMain",contentMain);
		view.addObject("contentId",contentId);
		view.addObject("fileUrlPrefix",propertiesService.getFileUrlPrefix());
	}

	/**
	 *
	 * @param contentId 内容id
	 * @return
	 */
	@GetMapping("/index.do")
    @Function("content.resContentChapter.query")
    @ResponseBody
    public ModelAndView index(int contentId) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        view.addObject("contentId",contentId);
		initContentMain(view,contentId);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("content.resContentChapter.edit")
    @ResponseBody
    public ModelAndView edit(Integer chapterId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        ResContentChapter resContentChapter = resContentChapterService.queryById(chapterId);
        view.addObject("resContentChapter", resContentChapter);
        initContentMain(view,resContentChapter.getContentId());
		try {
			view.addObject("resContentChapterJson", JacksonUtils.toJsonString(resContentChapter,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("content.resContentChapter.add")
    @ResponseBody
    public ModelAndView add(int contentId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
	    ResContentChapter resContentChapter = new ResContentChapter();
	    resContentChapter.setContentId(contentId);
	    initContentMain(view,contentId);
	    view.addObject("contentId",contentId);
	    //查询最大章节序号
	    int maxNo = resContentChapterService.selectMaxChapterNo(contentId);
	    maxNo++;
	    view.addObject("chapterNo",maxNo);
		resContentChapter.setChapterNo(maxNo);
	    //查询在内容里面定义的单章价格
	    ResContentMain main = contentMainService.queryById(contentId);
	    if (main.getChapterPrice()!=null && main.getChapterPrice().doubleValue()>0) {
			view.addObject("chapterPrice",main.getChapterPrice().setScale(2));
			resContentChapter.setChapterPrice(main.getChapterPrice());
	    }
	    if (main.getFreeChapters()!=null && main.getFreeChapters().intValue()>0
			    && main.getFreeChapters().intValue()>=maxNo) {
	    	resContentChapter.setFreeFlag(1);
	    } else {
	    	resContentChapter.setFreeFlag(0);
	    }
	    resContentChapter.setChapterStatus(1);
	    view.addObject("resContentChapter", resContentChapter);
	    try {
		    view.addObject("resContentChapterJson", JacksonUtils.toJsonString(resContentChapter,JacksonUtils.DF1));
	    } catch (JsonProcessingException e) {
		    e.printStackTrace();
	    }
	    return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("content.resContentChapter.query")
    @ResponseBody
    public JsonResult<PageQuery> list(ResContentChapterQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        resContentChapterService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,ResContentChapter resContentChapter,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			resContentChapter.setCreatedBy(user.getId().intValue());
			resContentChapter.setCreatedName(user.getName());
			resContentChapter.setCreatedTime(new Date());
			resContentChapter.setViewCount(0);
			resContentChapter.setOrderCount(0);
		    //上传文件到视频云
			resContentChapterService.save(resContentChapter);
		} else {
			resContentChapter.setUpdatedBy(user.getId().intValue());
			resContentChapter.setUpdatedName(user.getName());
			resContentChapter.setUpdatedTime(new Date());
			resContentChapterService.updateTemplate(resContentChapter);
		}

		return result;
	}
    @PostMapping("/add.json")
    @Function("content.resContentChapter.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ResContentChapter resContentChapter,HttpServletRequest request)
    {

        return save(true,resContentChapter,request);
    }

    @PostMapping("/update.json")
    @Function("content.resContentChapter.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ResContentChapter resContentChapter,HttpServletRequest request) {
		return save(false,resContentChapter,request);
    }

	@PostMapping("/upload.json")
	@Function("content.resContentChapter.upload")
	@ResponseBody
    public JsonResult<String> upload(MultipartFile file,Integer chapterId,String filePath,Integer contentId) {
    	JsonResult<String> result = null;
		String dir = DateUtil.now("yyyyMMdd");
		String subPath = "/video/course/"+dir+"/"+contentId+"/";
		if (!FileUtils.isEmptyFile(file)) {
			try
			{
				String filePathFileNamePair = FileUtils.upload(subPath,file);
				String filePathStoreFile = filePathFileNamePair.split("::")[0];
				filePathStoreFile = subPath+filePathStoreFile;
				if (chapterId==null && StringUtils.isNotEmpty(filePath)) {
					//新增未保存章节，已经上传了视频文件，删除原来的
					FileUtils.deleteFile(filePath);
				}
				if (chapterId!=null) {
					ResContentChapter chapter = resContentChapterService.queryById(chapterId);
					if (chapter!=null) {
						String oldFilePath = chapter.getFilePath();
						if (StringUtils.isNotEmpty(oldFilePath)) {
							FileUtils.deleteFile(oldFilePath);
						}
						//更新文件
						ResContentChapter chapterUp = new ResContentChapter();
						chapterUp.setChapterId(chapterId);
						chapterUp.setFilePath(filePathStoreFile);
						resContentChapterService.updateTemplate(chapterUp);
						//上传新的远程文件,更新视频发布地址
						chapter.setFilePath(filePathStoreFile);

						chapterUp = uploadRemote(chapter);
						resContentChapterService.updateTemplate(chapterUp);

						//删除旧的远程文件

					}
				}
				result = JsonResult.success(filePathStoreFile);
			}catch(Exception e) {
				e.printStackTrace();
				result = JsonResult.fail();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		return result;
    }

    private ResContentChapter uploadRemote(ResContentChapter chapter) throws Exception {
    	String root = FileUtils.getRoot();
	    VodUploadCommitResponse response = TencentVideoApi.uploadFile(root+chapter.getFilePath());
	    String jsonStr = TencentVideoApi.getVideoInfo(response.getFileId());
	    JSONObject jo = JSON.parseObject(jsonStr);
		JSONObject basicInfo = jo.getJSONObject("basicInfo");
		int duration = basicInfo.getIntValue("duration");
		String sourceVideoUrl = basicInfo.getString("sourceVideoUrl");

	    ResContentChapter resContentChapter = new ResContentChapter();
	    resContentChapter.setChapterId(chapter.getChapterId());
	    resContentChapter.setPlayUrl(sourceVideoUrl);
	    resContentChapter.setChapterDuration(duration);
	    resContentChapter.setFileId(response.getFileId());
	    if (chapter.getFreeDuration()>duration) {
	    	resContentChapter.setFreeDuration(duration);
	    }
		if (chapter.getFreeFlag()==1 || chapter.getFreeDuration()>0) {
			//试播地址，有效期至2040年
			Calendar cal = Calendar.getInstance();
			cal.set(2040, 12, 31);
			long t = cal.getTime().getTime()/1000;
			int exper = chapter.getFreeDuration();
			if (chapter.getFreeFlag()==1 || chapter.getFreeDuration()==duration) {
				//免费视频
				exper = 0;
			}
			String freeUrl = TencentVideoApi.getPlayUrl(sourceVideoUrl,t,exper,0);
			resContentChapter.setPreviewUrl(freeUrl);
		}
		return resContentChapter;
	    /**
	     * {
	     "code": 0,
	     "message": "",
	     "codeDesc": "Success",
	     "basicInfo": {
	     "name": "xx.mp4",
	     "size": 27304132,
	     "totalSize": 27304132,
	     "duration": 313,
	     "description": "",
	     "status": "normal",
	     "createTime": 1539675204,
	     "updateTime": 1539675205,
	     "expireTime": 0,
	     "classificationId": 0,
	     "classificationName": "其他",
	     "playerId": 133157,
	     "coverUrl": "",
	     "type": "mp4",
	     "sourceVideoUrl": "http://1256643784.vod2.myqcloud.com/199edf8dvodgzp1256643784/8685fcfb5285890782385186656/L3lhbQuRRG4A.mp4",
	     "tags": [ ],
	     "sourceInfo": null,
	     "sourceContext": "",
	     "region": "gzp",
	     "storageMode": 0,
	     "sourceType": 3,
	     "classificationPath": "其他"
	     }
	     }
	     */
    }
    @GetMapping("/view.json")
    @Function("content.resContentChapter.query")
    @ResponseBody
    public JsonResult<ResContentChapter>queryInfo(Integer chapterId) {
        ResContentChapter resContentChapter = resContentChapterService.queryById( chapterId);
        return  JsonResult.success(resContentChapter);
    }

    @PostMapping("/delete.json")
    @Function("content.resContentChapter..del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        resContentChapterService.batchDelResContentChapter(idList);
        return JsonResult.success();
    }

    

}
